package main

import (
	"fmt"
	"net"
	"os"
)

func main() {
	var (
		host   = "127.0.0.1"
		port   = "6666"
		remote = host + ":" + port
		data   = make([]byte, 1024)
	)

	fmt.Println("Initiating server...(Ctrl+c to stop)")
	lis, err := net.Listen("tcp", remote)
	//defer lis.Close()  这句用了就内存出问题
	if err != nil {
		fmt.Println("Error when listen:", remote)
		os.Exit(-1)
	}
	fmt.Println("starting the server")

	for {
		var res string
		conn, err := lis.Accept()
		if err != nil {
			fmt.Println("Error accepting client: ", err.Error())
			os.Exit(0)
		}
		go func(con net.Conn) {
			defer con.Close()
			for {
				length, err := con.Read(data)
				if err != nil {
					fmt.Printf("Client %v quit\n", con.RemoteAddr())
					con.Close()
					return
				} else {
					res = string(data[0:length])
					fmt.Printf("%s said: %s\n", con.RemoteAddr(), res)
					res = "You said:" + res
					con.Write([]byte(res))
				}
			}
		}(conn)
	}

}
